import React, { useState, useEffect } from 'react';
import { Badge, Popover, List, Typography, Space, Spin, Empty, Button } from 'antd';
import { BellOutlined, CheckOutlined, DownOutlined, UpOutlined } from '@ant-design/icons';
import { notificationAPI } from '../utils/api';
import { useAuth } from '../context/AuthContext';
import './NotificationIcon.css';

const { Text } = Typography;

const NotificationIcon = () => {
  const [unreadCount, setUnreadCount] = useState(0);
  const [notifications, setNotifications] = useState([]);
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [expandedItems, setExpandedItems] = useState(new Set());
  const { user } = useAuth();

  // 获取未读通知数量
  const fetchUnreadCount = async () => {
    try {
      const response = await notificationAPI.getUnreadCount();
      setUnreadCount(response.unread_count || 0);
    } catch (error) {
      console.error('获取未读通知数量失败:', error);
    }
  };

  // 获取用户通知列表
  const fetchNotifications = async () => {
    if (!user) return;
    
    setLoading(true);
    try {
      const response = await notificationAPI.getUserNotifications({
        limit: 20,
        offset: 0
      });
      setNotifications(response.notifications || []);
    } catch (error) {
      console.error('获取通知列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 标记通知为已读
  const handleMarkAsRead = async (notificationId) => {
    try {
      await notificationAPI.markAsRead(notificationId);
      // 更新本地状态
      setNotifications(prev => 
        prev.map(item => 
          item.id === notificationId 
            ? { ...item, is_read: true, read_at: new Date().toISOString() }
            : item
        )
      );
      // 更新未读数量
      setUnreadCount(prev => Math.max(0, prev - 1));
    } catch (error) {
      console.error('标记已读失败:', error);
    }
  };

  // 处理通知点击
  const handleNotificationClick = (notification) => {
    if (!notification.is_read) {
      handleMarkAsRead(notification.id);
    }
  };

  // 切换展开/收起状态
  const toggleExpanded = (notificationId, e) => {
    e.stopPropagation();
    console.log('Toggling expansion for notification:', notificationId);
    setExpandedItems(prev => {
      const newSet = new Set(prev);
      if (newSet.has(notificationId)) {
        newSet.delete(notificationId);
        console.log('Collapsing notification:', notificationId);
      } else {
        newSet.add(notificationId);
        console.log('Expanding notification:', notificationId);
      }
      console.log('New expanded items:', Array.from(newSet));
      return newSet;
    });
  };

  // 检查内容是否需要展开功能
  const needsExpansion = (content) => {
    if (!content) return false;
    // 降低阈值：如果内容超过50个字符，认为需要展开功能
    const needs = content.length > 50;
    console.log('Content:', content);
    console.log('Content length:', content.length, 'Needs expansion:', needs);
    return needs;
  };

  // 初始化时获取未读数量
  useEffect(() => {
    if (user) {
      fetchUnreadCount();
    }
  }, [user]);

  // 定期刷新未读数量
  useEffect(() => {
    if (!user) return;
    
    const interval = setInterval(fetchUnreadCount, 30000); // 30秒刷新一次
    return () => clearInterval(interval);
  }, [user]);

  // 通知列表内容
  const notificationContent = (
    <div className="notification-popover">
      <div className="notification-header">
        <Text strong>通知</Text>
        {unreadCount > 0 && (
          <Text type="danger" className="unread-badge">
            {unreadCount} 条未读
          </Text>
        )}
      </div>
      
      {loading ? (
        <div className="notification-loading">
          <Spin size="small" />
          <Text>加载中...</Text>
        </div>
      ) : notifications.length > 0 ? (
        <List
          className="notification-list"
          dataSource={notifications}
          renderItem={(item) => (
            <List.Item
              className={`notification-item ${!item.is_read ? 'unread' : ''}`}
              onClick={() => handleNotificationClick(item)}
            >
              <div className="notification-content">
                <div className="notification-title">
                  <Text strong={!item.is_read}>{item.title}</Text>
                  {!item.is_read && <div className="unread-dot" />}
                </div>
                {item.content && (
                  <div className="notification-body">
                    <Text 
                      type="secondary" 
                      className={`notification-text ${expandedItems.has(item.id) ? 'expanded' : 'collapsed'}`}
                    >
                      {item.content}
                    </Text>
                    {needsExpansion(item.content) && (
                      <Button
                        type="link"
                        size="small"
                        className="expand-button"
                        onClick={(e) => toggleExpanded(item.id, e)}
                        icon={expandedItems.has(item.id) ? <UpOutlined /> : <DownOutlined />}
                      >
                        {expandedItems.has(item.id) ? '收起' : '展开'}
                      </Button>
                    )}
                  </div>
                )}
                <div className="notification-meta">
                  <Text type="secondary" className="notification-time">
                    {new Date(item.created_at).toLocaleString()}
                  </Text>
                  {!item.is_read && (
                    <CheckOutlined 
                      className="mark-read-icon"
                      onClick={(e) => {
                        e.stopPropagation();
                        handleMarkAsRead(item.id);
                      }}
                    />
                  )}
                </div>
              </div>
            </List.Item>
          )}
        />
      ) : (
        <Empty 
          description="暂无通知" 
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          className="notification-empty"
        />
      )}
    </div>
  );

  if (!user) return null;

  return (
    <Popover
      content={notificationContent}
      title={null}
      trigger="click"
      visible={visible}
      onVisibleChange={setVisible}
      placement="bottomRight"
      overlayClassName="notification-popover-overlay"
      onOpenChange={(open) => {
        setVisible(open);
        if (open) {
          fetchNotifications();
        }
      }}
    >
      <Badge count={unreadCount} offset={[-5, 5]} className="notification-badge">
        <BellOutlined className="notification-icon" />
      </Badge>
    </Popover>
  );
};

export default NotificationIcon;
